package com.hxd.otc.net;

import android.os.AsyncTask;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.event.Event;
import com.hxd.otc.utils.CollectionUtil;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 暂时无用
 */
public class PingBaseUrl extends AsyncTask<String, String, String> {

    private boolean isFinish;

    OkHttpClient client = new OkHttpClient();


    public PingBaseUrl() {
    }

    @Override
    protected String doInBackground(String... strings) {
        if (CollectionUtil.isEmpty(RetrofitManager.mUrlList)) {
            getUrlList();
        }
        for (int i = 0; i < RetrofitManager.mUrlList.size(); i++) {
            request(i);
        }
        return null;
    }

    /**
     * 轮训 PING  域名
     *
     * @param i
     */
    private void request(final int i) {

        final String url = RetrofitManager.getUrl(i) + "ping";

        LogUtils.e("===ping===url=====1=====" + url + " , i : " + i);

        Request request = new Request.Builder().url(url).addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8").build();

        if (RetrofitManager.getUrl(i).equals(UIUtils.getContext().getString(R.string.main_base_url))) {
            client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);//主路径 超时时间设置的长一点
        } else {
            client.newBuilder().connectTimeout(2, TimeUnit.SECONDS);//其他设置两秒
        }

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("===onFailure===url======1====" + url + " , i : " + i);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (200 == response.code()) {
                    LogUtils.e("===onResponse===url======2====" + url + " , i : " + i);
                    setBaseUrlList(i);
                }
            }

        });
    }

    private synchronized void setBaseUrlList(int index) {
        if (isFinish || index < 0 || index > RetrofitManager.mUrlList.size()) {
            return;
        }
        isFinish = true;
        LogUtils.e("===setBaseUrlList=======" + index);
        BaseApplication.SERVER_HOST = index;
        // 跳转到引导页
        EventBus.getDefault().post(new Event.StartActivityEvent());
    }


    private void getUrlList() {
        String[] urlArray = UIUtils.getContext().getResources().getStringArray(R.array.base_url);
        RetrofitManager.mUrlList.clear();
        RetrofitManager.mUrlList.addAll(Arrays.asList(urlArray));
    }
}
